package com.home.security.app;

import com.home.security.app.config.KeyConfiguration;
import com.home.security.app.exception.ClientTokenException;
import com.home.security.app.token.IJWTInfo;
import com.home.security.app.token.JWTHelper;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * Description: 生成 token/ 解析 token
 * Created by 王大宸 on 2020-12-11 11:45
 * Created with IntelliJ IDEA.
 */
@Component
public class JwtTokenUtil {

    @Value("${jwt.expire}")
    private int expire;

    public int getExpire() {
        return expire;
    }

    @Autowired
    private JWTHelper jwtHelper;

    @Autowired
    private KeyConfiguration keyConfiguration;

    /***
     * 功能说明：生成 token
     *
     * @author 王大宸
     * @date 2020/12/11 13:48
     * @param jwtInfo      认证主体信息
     * @param otherInfo    认证附加信息
     * @param expireTime   过期时间
     * @return java.lang.String
     */
    public String generateToken(IJWTInfo jwtInfo, Map<String, String> otherInfo, Date expireTime) throws Exception {
        return jwtHelper.generateToken(jwtInfo, keyConfiguration.getUserPriKey(), expireTime, otherInfo);
    }

    /***
     * 功能说明：解析 token
     *
     * @author 王大宸
     * @date 2020/12/11 13:48
     * @param token  需要解析的 token
     * @return com.home.security.app.token.IJWTInfo
     */
    public IJWTInfo getInfoFromToken(String token) throws Exception {
        try {
            IJWTInfo infoFromToken = jwtHelper.getInfoFromToken(token, keyConfiguration.getUserPubKey());
            Date current = infoFromToken.getExpireTime();
            if (new Date().after(current)) {
                throw new ClientTokenException("访问令牌已过期!");
            }
            return infoFromToken;
        } catch (ExpiredJwtException ex) {
            throw new ClientTokenException("访问令牌已过期!");
        } catch (SignatureException ex) {
            throw new ClientTokenException("访问令牌签名错误!");
        } catch (IllegalArgumentException ex) {
            throw new ClientTokenException("访问令牌为空!");
        } catch (Exception e) {
            throw new ClientTokenException("访问令牌错误!");
        }

    }

}
